package com.markyao.controller;

import com.markyao.dao.pojo.User;
import com.markyao.service.UserService;
import com.markyao.vo.Result;
import com.markyao.vo.parmas.UserParmas;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("users")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("add")
    public Result register(@RequestBody UserParmas userParmas){
        Result result = userService.addUser(userParmas);
        return result;
    }

    @PostMapping("login")
    public Result login(@RequestBody UserParmas userParmas, HttpSession session, HttpServletResponse response, HttpServletRequest request){
        //登录,service会创建token并存入redis
        System.out.println("控制层-->"+userParmas);
        Result login = userService.login(userParmas);
        response.setHeader("Authorization", (String) login.getData());
        return login;
    }

    @GetMapping("logout")
    public Result logout(HttpSession session){
        //清除session
        session.removeAttribute("user");
        return new Result(true,"退出登录",000,null);
    }

    @PostMapping("changePwd")
    public Result changePwd(@RequestBody UserParmas userParmas,HttpSession session){
        User user = (User) session.getAttribute("user");
        if(user==null){
            return new Result(false, "用户错误",0000,null);
        }
        userParmas.setUsername(user.getUsername());
        //修改密码
        return userService.changePwd(userParmas);
    }

    @GetMapping("getByUid")
    public Result getByUid(HttpSession session){
        return userService.findByUid(getUserBySession(session).getUid());

    }

    @PostMapping("changeinfo")
    public Result changeinfo(@RequestBody UserParmas userParmas){
        System.out.println(userParmas);
        return userService.updateInfo(userParmas);
    }
    private User getUserBySession(HttpSession session) {
        return (User)session.getAttribute("user");
    }


}
